import { Form, DatePicker, Button, Space, Modal,Select } from "antd";
import React, { useRef, useState, useEffect } from "react"; 
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import { apiDynamicInfoPage, apiDynamicInfoDel, apiDynamicLabelList, apiDynamicInfoDynamicExport } from '@/request/pet'
import TheImage from '@/components/TheImage'
import { getDateTime3 } from '@/utils/getDate'
import VideoPlayer from "@/components/VideoPlayer"
import { exportSheetTable } from '@/utils/exportTable.js'
import _ from 'lodash'

const { RangePicker } = DatePicker;

const SearchHeader = ({ setValue }) => {
  const formRef = useRef()
  const [options, setOptions] = useState([])
  useEffect (async() => {
    let res = await apiDynamicLabelList()
    if(res.code === 0){
      let option = res.data.map(v => {
        return{
          value: v.labelId,
          label: v.labelName
        }
      })
      setOptions(option)
    }
    
  }, [])
  const onFinish = values => {
    if (values.time && values.time.length) {
      values.startDate = getDateTime3(values.time[0]) + ' 00:00:00'
      values.endDate = getDateTime3(values.time[1]) + ' 23:59:59'
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    setValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({ time: [], labelIds: '' })
    setValue({})
  }
  return (
    <div
      className="p-search-box"
      style={{ display: "flex", justifyContent: "space-between" }}
    >
      <Form onFinish={onFinish} ref={formRef}>
        <Space>
          <Form.Item label="发表时间" name="time">
            <RangePicker />
          </Form.Item>
          <Form.Item name={"labelIds"} label="动态标签">
            <Select
              style={{ width: 140 }}
              options={options}
              placeholder={"动态标签"}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">搜索</Button>
              <Button onClick={reset}>重置</Button>
            </Space>
          </Form.Item>
        </Space>
      </Form>
    </div>
  );
};

class List extends React.Component {
  state = {
    down_loading: false,
    columns: [
      {
        title: "用户昵称",
        dataIndex: "nickName",
        key: "nickName",
      },
      {
        title: "动态标签",
        dataIndex: "labelIds",
        key: "labelIds",
      },
      {
        title: "点赞数",
        dataIndex: "likeNum",
        key: "likeNum",
      },
      {
        title: "评论数",
        dataIndex: "comments",
        key: "comments",
      },
      {
        title: "发表时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "正文",
        dataIndex: "dynamicText",
        key: "dynamicText",
        render: (text, render) => {
          return <p style={{ width: 200, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{render.dynamicText}</p>
        }
      },
      {
        title: "图片",
        dataIndex: "dynamicImages",
        key: "dynamicImages",
        render: (text, render) => {
          if (render.type === "video") {
            let arr = render.dynamicImages.split('|')
            return <TheImage preview={false} src={arr[1]} width={80} height={80} onClick={() => { this.videoDialog(arr[0]) }} />
          } else {
            let arr = render.dynamicImages.split(',')
            return <Space>
              {
                arr.map(v => {
                  return <TheImage src={v} width={80} height={80} />
                })
              }
            </Space>
          }
        }
      },
      {
        title: "操作",
        render: (text, render) => {
          return (
            <div>
              <TheButton haspermi={['pet:list:details']} onClick={() => this.props.history.push(`/pet/comments/${render.dynamicId}`)}>查看评论</TheButton>
              <TheButton haspermi={['pet:list:delete']} onClick={() => this.delConfirm(render.dynamicId)}>删除</TheButton>
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    searchValue: '',
    isvideoModalVisible: false,
    videoAddress: ""
  };
  async componentDidMount() {
    await this.getData()
  }
  getDynamicText = (value) => {
    console.log(value.length)
    // if (value.length >= 20) {
    //   return value.subString(0, 20) + '...'
    // } else {
    //   return value
    // }
  }
  getData = async () => {
    const { pageData, searchValue } = this.state
    let res = await apiDynamicInfoPage({ ...pageData, ...searchValue })
    if (res.data && res.code === 0) {
      this.setState({
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount,
        dataSource: res.data
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  videoDialog = (e) => {
    this.setState({
      isvideoModalVisible: true,
      videoAddress: e
    })
  }
  videoOk = async () => {
    this.setState({
      isvideoModalVisible: false,
      videoAddress: ""
    })
  }
  setValue = (value) => {
    this.setState({ searchValue: value, pageData: { pageNo: 1, pageSize: 10 } }, () => this.getData())
  }
  delConfirm = (dynamicId) => {
    React.$confirm({
      title: '您确认删除此条动态吗？',
      onOk: async () => {
        let res = await apiDynamicInfoDel({ dynamicId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      }
    })
  }
  // 导出
  toExportTable = async () =>{
    this.setState({ down_loading: true })
    await apiDynamicInfoDynamicExport({ ...this.state.searchValue }).then(res => {
      if(res.code === 0 && res.data.length > 0){
        let tH_data = [
          {
            title: '动态列表',
            prop: '',
            children: [
              { prop: 'nickName', title: '用户昵称'},
              { prop: 'labelIds', title: '动态标签'},
              { prop: 'likeNum', title: '点赞数', valueType:'number'},
              { prop: 'comments', title: '评论数', valueType:'number'},
              { prop: 'createTime', title: '发表时间'},
              { prop: 'dynamicText', title: '正文'},
            ]
          }
        ]
        let tB_data = res.data.map(item => {
          return{
            nickName: item.nickName,
            labelIds: item.labelIds,
            likeNum: item.likeNum,
            comments: item.comments,
            createTime: item.createTime,
            dynamicText: item.dynamicText,
          }
        })
        this.setState({ down_loading: false })
        exportSheetTable({
          fileName: '动态列表', tH_data: tH_data, tB_data: tB_data, isSheet: true, merge: false
        })
      }
    }).catch(err => {
      React.$message({
        type: 'warning',
        content: '导出操作失败,请重试'
      })
      this.setState({ down_loading: false })
    })
  }
  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total, isvideoModalVisible, videoAddress
    } = this.state;
    return (
      <div className="p-layout-box">
        <SearchHeader history={this.props.history} setValue={this.setValue} />
        <div style={{margin:'5px'}}>
        <TheButton size="middle" type="default" haspermi={['pet:list:export']} onClick={() => this.toExportTable()} >导出</TheButton>
        </div>
        <div className="p-layout-content-pagination">
          <TheTable scroll={{ x: 'max-content', y: '63vh' }} columns={columns} dataSource={dataSource} />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
        {isvideoModalVisible ?
          <Modal visible={isvideoModalVisible} onOk={this.videoOk} onCancel={this.videoOk}>
            <VideoPlayer src={videoAddress} />
          </Modal> : null}
      </div>
    );
  }
}

export default List;
